package com.farm.configer.form.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;

import com.farm.configer.domain.Configer;
import com.farm.configer.domain.Configerform;
import com.farm.configer.domain.ex.ConfigerMetaPara;
import com.farm.configer.domain.ex.FieldTypeEnum;
import com.farm.configer.domain.ex.TableField;
import com.farm.configer.form.FormModel;
import com.farm.configer.form.FormModelUtils;
import com.farm.configer.service.ConfigerServiceInter;
import com.farm.core.page.ViewMode;
import com.farm.parameter.FarmParameterService;
import com.farm.util.spring.BeanFactory;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.create.table.ColumnDefinition;
import net.sf.jsqlparser.statement.create.table.CreateTable;
import net.sf.jsqlparser.statement.create.table.Index;
import net.sf.jsqlparser.statement.create.table.Index.ColumnParams;

/**
 * 自定义模型(通过用户在界面手动录入)
 * 
 * @author Wd
 *
 */
public class SqlParseConfigerModelImpl extends FormModelUtils implements FormModel {
	private ConfigerServiceInter configerServiceImpl = (ConfigerServiceInter) BeanFactory
			.getBean("configerServiceImpl");
	private Configer configer;

	public SqlParseConfigerModelImpl(Configer configer) {
		this.configer = configer;
	}

	@Override
	public String getFormPageUrl() {
		return "confweb/baseForm.do?configerid=" + configer.getId();
	}

	@Override
	public String getFormPageSubmitUrl() {
		return "confweb/baseSubmitForm.do?configerid=" + configer.getId();
	}

	@Override
	public ModelAndView getFormPageModelAndView(List<ConfigerMetaPara> testParaList, Object jspConfiger) {
		List<Configerform> forms = configerServiceImpl.getForms(configer.getId(), null);

		return ViewMode.getInstance().putAttr("forms", forms).putAttr("attrs", jspConfiger)
				.returnModelAndView("web-configer-forms/commons/baseForm");
	}

	@Override
	public Map<String, Object> submitForm(List<ConfigerMetaPara> paraList) {
		Map<String, Object> configerMap = new HashMap<String, Object>();
		Map<String, Object> paras = new HashMap<String, Object>();
		try {
			for (ConfigerMetaPara node : paraList) {
				if (node.getCode().equals("sql")) {
					paras.put("sql", node.getJsonString());
					paras.put("table", parseSql(node.getJsonString()));
				} else {
					paras.put(node.getCode(), node.getJsonString());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			paras.put("ERROR", e.getMessage() + e);
		}
		configerMap.put(configer.getCode(), paras);
		return configerMap;
	}

	// 解析sql脚本
	private Map<String, Object> parseSql(String sql) {
		List<TableField> list = new ArrayList<TableField>();
		Map<String, TableField> map = new LinkedHashMap<String, TableField>();
		Map<String, Object> paras = new HashMap<String, Object>();
		Map<String, String> fieldTitleDic = FarmParameterService.getInstance().getDictionary("CBTG_CONFIG_CODETITLE");
		try {
			// 解析 SQL 语句
			Statement statement = CCJSqlParserUtil.parse(sql);
			// 确保我们处理的是 CREATE TABLE 语句
			if (statement instanceof CreateTable) {
				CreateTable createTable = (CreateTable) statement;
				// 获取表名
				Table table = createTable.getTable();
				paras.put("name", table.getName());
				// 获取列信息
				for (ColumnDefinition node : createTable.getColumnDefinitions()) {
					try {

						TableField tableField = new TableField();
						tableField.setCode(node.getColumnName());
						tableField.setLen(getColumnLen(node));
						tableField.setFormType("text");
						if (tableField.getLen() > 100) {
							tableField.setFormType("textarea");
						}
						if (tableField.getLen() < 3) {
							tableField.setFormType("select");
						}
						tableField.setPrimary(false);
						if (tableField.getLen() > 32) {
							tableField.setQueryType("like");
						} else {
							tableField.setQueryType("NONE");
						}
						tableField.setRequired(isColumnRequired(node));
						String title = fieldTitleDic.get(node.getColumnName());
						if (StringUtils.isNotBlank(title)) {
							tableField.setTitle(title);
						} else {
							tableField.setTitle(node.getColumnName());
						}
						tableField.setType(node.getColDataType().getDataType());
						list.add(tableField);
						map.put(tableField.getCode(), tableField);
					} catch (Exception e) {
						e.printStackTrace();
						throw new RuntimeException("SQL解析錯誤：错误字段：" + node.getColumnName() + " | " + e.getMessage() + e);
					}
				}
				// 获取索引信息
				List<Index> indexes = createTable.getIndexes();
				if (!indexes.isEmpty()) {
					for (Index index : indexes) {
						if (index.getType().indexOf("primary") >= 0) {
							for (ColumnParams para : index.getColumns()) {
								TableField tableField = map.get(para.getColumnName());
								if (tableField != null) {
									tableField.setPrimary(true);
								}
							}
						}
					}
				}
			} else {
				throw new RuntimeException("the sql is not CreateTable");
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		paras.put("fields", list);
		return paras;
	}

	private int getColumnLen(ColumnDefinition node) {
		try {
			String intVal = "0";
			if (node.getColDataType().getArgumentsStringList() != null
					&& node.getColDataType().getArgumentsStringList().size() > 0) {
				intVal = node.getColDataType().getArgumentsStringList().get(0);
			} else {
				FieldTypeEnum type = FieldTypeEnum.get(node.getColDataType().getDataType());
				if (type != null) {
					intVal = "" + type.getLen();
				}
			}
			if (intVal.matches("-?\\d+")) {
				return Integer.valueOf(intVal);
			} else {
				return 0;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}

	private boolean isColumnRequired(ColumnDefinition node) {
		if (node.getColumnSpecs() != null && node.getColumnSpecs().size() > 0) {
			return node.getColumnSpecs().get(0).equals("not");
		}
		return false;
	}

	@Override
	public List<Configerform> getForms() {
		List<Configerform> list = new ArrayList<Configerform>();
		Configerform sqlInput = new Configerform();
		sqlInput.setName("SQL表创建脚本");
		sqlInput.setCode("sql");
		sqlInput.setModel("textarea");
		sqlInput.setValid("none");
		sqlInput.setSort(1);
		sqlInput.setPcontent("sql脚本");
		sqlInput.setConfigerid(configer.getId());
		list.add(sqlInput);
		Configerform sqltype = new Configerform();
		sqltype.setName("SQL模型");
		sqltype.setCode("type");
		sqltype.setModel("select");
		sqltype.setValid("none");
		sqltype.setSort(2);
		sqltype.setEnums("mysql,tsql");
		sqltype.setConfigerid(configer.getId());
		list.add(sqltype);
		return list;
	}

}
